package handler

import (
	"fmt"
	"google.golang.org/protobuf/reflect/protoreflect"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	"sen-golang-study/go_game_study/hero_story_go_server/common/server_msg"
)

type CmdContextInnerWebsocket struct {
	Id              string
	GatewayId       uint32
	RemoteSessionId uint32
	UserId          uint32
	ClientIpAddr    string
	MsgChan         chan *server_msg.InternalServerMsg
	LastActiveTime  int64
}

func (ctx *CmdContextInnerWebsocket) GetId() string {
	return ctx.Id
}

func (ctx *CmdContextInnerWebsocket) SetId(id string) {
	ctx.Id = fmt.Sprintf("%d_%d", ctx.GatewayId, ctx.RemoteSessionId)
}

func (ctx *CmdContextInnerWebsocket) BindUserId(val uint32) {
	ctx.UserId = val
}

func (ctx *CmdContextInnerWebsocket) GetUserId() uint32 {
	return ctx.UserId
}

func (ctx *CmdContextInnerWebsocket) GetClientIpAddr() string {
	return ctx.ClientIpAddr
}

func (ctx *CmdContextInnerWebsocket) SetSessionId(sessionId uint32) {
	ctx.RemoteSessionId = sessionId
}

func (ctx *CmdContextInnerWebsocket) GetSessionId() uint32 {
	return ctx.RemoteSessionId
}

func (ctx *CmdContextInnerWebsocket) Write(msgObj protoreflect.ProtoMessage) {
	byteArray, err := server_msg.Encode(msgObj)

	if nil != err {
		log.Error("Encode msg err %+v \n", err)
		return
	}

	innerMsg := &server_msg.InternalServerMsg{}
	innerMsg.GatewayId = ctx.GatewayId
	innerMsg.SessionId = ctx.RemoteSessionId
	innerMsg.UserId = ctx.UserId
	innerMsg.MsgData = byteArray

	ctx.MsgChan <- innerMsg
}

func (ctx *CmdContextInnerWebsocket) SendError(errorCode int, errorMsg string) {
}

func (ctx *CmdContextInnerWebsocket) Disconnect() {
	disconnectMsg := &server_msg.InternalServerMsg{
		GatewayId:  ctx.GatewayId,
		SessionId:  ctx.GetSessionId(),
		UserId:     ctx.UserId,
		Disconnect: 1,
		MsgData:    nil,
	}

	ctx.MsgChan <- disconnectMsg
}
